import { ComponentFactoryResolver, Injector } from '@angular/core';
import { MessagerService } from '@farris/ui-messager';
import { BsModalService } from '@farris/ui-modal';
import { NotifyService } from '@farris/ui-notify';
import { ControlContextMenuItem } from '../../../../../entity/control-context-menu';
import { EventEditorService,DomService, RefreshFormService } from '@farris/designer-services';
import { DgControl } from '../../../../../utils/dg-control';
import { ListFilterFieldsEditorComponent } from '../../../../filter/list-filter/property/editor/list-filter-fields-editor/list-filter-fields-editor.component';
import { ListFilterBuilderService } from '../../../../filter/list-filter/context-menu/filter-builder';
import { FarrisDesignBaseComponent } from '@farris/designer-element';

/**
 * 列表启用/移除筛选条相关服务
 */
export class DataGridFilterContextMenuService {

    private domService: DomService;
    private messagerService: MessagerService;
    public refreshFormService: RefreshFormService;
    private notifyService: NotifyService;
    private modalService: BsModalService;
    private resolver: ComponentFactoryResolver;
    private eventEditorService:EventEditorService;
    constructor(private injector: Injector) {

        this.domService = this.injector.get(DomService);
        this.eventEditorService = this.injector.get(EventEditorService);
        this.notifyService = this.injector.get(NotifyService);
        this.refreshFormService = this.injector.get(RefreshFormService);
        this.messagerService = this.injector.get(MessagerService);
        this.modalService = this.injector.get(BsModalService);
        this.resolver = this.injector.get(ComponentFactoryResolver);
    }

    /**
     * 组装筛选条菜单
     * @param viewModelId 列表所在视图模型id
     * @param menuConfig 当前菜单数据
     */
    assembleListFilterMenu(viewModelId: string, menuConfig: ControlContextMenuItem[]) {
        const listFilterMenu = menuConfig.find(menu => menu.id === DgControl.ListFilter.type);
        if (!listFilterMenu) {
            return menuConfig;
        }

        // 若不能启用筛选条，则移除菜单(表格绑定子实体，不支持启用筛选条)
        if (!this.checkCanEnableListFilter(viewModelId)) {
            menuConfig = menuConfig.filter(menu => menu.id !== DgControl.ListFilter.type);
            return menuConfig;
        }

        const gridComponent = this.domService.getComponentByVMId(viewModelId);
        let listFilterExisted = false;

        // 筛选条(目前的表单筛选条认为在列表组件内部)
        if (this.checkControlExistByType(DgControl.ListFilter.type, gridComponent.id)) {
            listFilterExisted = true;
        }

        if (listFilterExisted) {
            listFilterMenu.title = '移除' + listFilterMenu.title;
            listFilterMenu.id = 'remove' + listFilterMenu.id;
        } else {
            listFilterMenu.title = '启用' + listFilterMenu.title;
            listFilterMenu.id = 'enable' + listFilterMenu.id;
        }

        return menuConfig;
    }


    /**
     * 弹出筛选条配置编辑器
     */
    openListFilterModal(viewModelId: string, dataGridId: string) {

        const compFactory = this.resolver.resolveComponentFactory(ListFilterFieldsEditorComponent);
        const compRef = compFactory.create(this.injector);

        const modalConfig = {
            title: '筛选条字段编辑器',
            width: 950,
            height: 500,
            showButtons: true,
            showMaxButton: true,
            buttons: compRef.instance.modalFooter
        };
        compRef.instance.value = [];
        compRef.instance.editorParams = {
            viewModelId,
            controlSource: 'normal'
        };
        compRef.instance.showPropertyPanel = false;

        const modalPanel = this.modalService.show(compRef, modalConfig);
        compRef.instance.closeModal.subscribe(() => {
            modalPanel.close();
        });
        compRef.instance.submitModal.subscribe((data) => {
            if (data && data.value) {
                const filterBuilderService = new ListFilterBuilderService(this.injector);
                filterBuilderService.createListFilterInDocument(data.value, viewModelId, dataGridId);

                this.notifyService.success('启用成功');
                this.refreshFormService.refreshFormDesigner.next();
            }
            modalPanel.close();
        });
    }


    /**
     * 校验是否可以启用筛选条
     */
    private checkCanEnableListFilter(viewModelId: string) {
        // 限定只有绑定主表的列表可以启用筛选条
        const viewModel = this.domService.getViewModelById(viewModelId);
        if (viewModel.bindTo !== '/') {
            return false;
        }

        // 校验是否启用过筛选方案，筛选方案和筛选条互斥，不能同时启用
        const querySchemeExisted = this.checkControlExistByType(DgControl.QueryScheme.type);

        return !querySchemeExisted;
    }

    /**
     * 移除列表上方的筛选条
     * @param viewModelId 列表所属视图模型ID
     * @param dataGridId 列表控件id
     */
    removeListFilter(viewModelId: string, cmpInstance: FarrisDesignBaseComponent) {
        this.messagerService.question('确定移除筛选条？', () => {
            const filterBuilderService = new ListFilterBuilderService(this.injector);
            filterBuilderService.removeListFilterInDocument(viewModelId);

            cmpInstance.emit('clearPropertyPanel');

            this.notifyService.success('已移除筛选条');
            this.refreshFormService.refreshFormDesigner.next();
        });

    }

    /**
     * 在指定组件内根据类型校验控件是否存在
     * @param controlType 控件类型
     * @param componentId 组件ID
     */
    private checkControlExistByType(controlType: string, componentId = 'root-component') {
        const rootCmp = this.domService.getComponentById(componentId);
        return this.domService.selectNode(rootCmp, item => item.type === controlType);
    }

}
